package com.icbc.controllers;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.icbc.model.Document;
import com.icbc.services.DocumentService;

@Controller
@RequestMapping("/search")
public class SearchController {

	@Autowired
	public DocumentService documentService;
	
	@RequestMapping(method=RequestMethod.POST)
    public String processForm(@ModelAttribute(value="tags") String tags, BindingResult result, ModelMap map){
        if(result.hasErrors()){
            return "document/search";
        }else{
        	if(tags.length()==0){
        		return "redirect:/document";
        	}
        	Collection<String> tagsCollection = new ArrayList<String>();
        	
        	String[] arrayString = tags.toLowerCase().split(" ");
        	
        	tagsCollection.addAll(Arrays.asList(arrayString));
        	
        	Collection<Document> col = documentService.getDocumentByTags(tagsCollection);
        	
        	map.addAttribute("documents", col);        	
        	
            return "document/index";
        }
	}
}